package dhz.storage.controllers;

import dhz.storage.util.Response;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.security.Security;
import java.util.HashMap;

@RestController
@RequestMapping("/disk")
@Api(tags = "网盘整体数据相关接口")
public class DiskControllers {
    static final Logger logger = LoggerFactory.getLogger(DiskControllers.class);
    /**
     * 给一个用户分配网盘有五个步骤，通过服务器上的一个脚本完成
     * 1. 使用useradd指令创建Linux用户
     * 2. 在quota中创建相关的配额
     * 3. 在samba中添加相关的用户
     * 4. 在相关位置添加文件夹
     * 5. 设置该文件夹权限
     * */
    @PostMapping("/allocate")
    @ApiOperation(value = "分配网盘", notes = "分配网盘的接口，用来给没有网盘的用户分配一个默认大小的网盘（5G），请注意一下自己电脑上的1KB是1024B还是1000B，可能在你的电脑上大小显示有问题")
    @ApiResponses({
            @ApiResponse(code = 1001, message = "网盘分配成功"),
            @ApiResponse(code = 500, message = "分配失败")
    })
    public Response allocateDisk(){
        String identification = SecurityUtils.getSubject().getPrincipal().toString();
        Response res;
        try{
            String[] allocate_cmd = {"/home/buaa/jobs/allocate", identification};
            Runtime.getRuntime().exec(allocate_cmd);
            res = new Response(1001, "网盘分配成功", null);
            return res;
        }catch(Exception e){
            res = new Response(500, "网盘分配失败", null);
            return res;
        }
    }

    @PostMapping("/hasDisk")
    @ApiOperation(value = "判断一个用户是不是已经有网盘了")
    @ApiResponses({
            @ApiResponse(code = 1001, message = "请求成功")
    })
    public Response hasDisk(){
        String identification = SecurityUtils.getSubject().getPrincipal().toString();
        File user_directory = new File("/mnt/students/"+identification);
        HashMap<String, Object> data = new HashMap<>();
        data.put("exist", user_directory.exists());
        return new Response(1001, data);
    }

    @PostMapping("/stat")
    @ApiOperation(value = "网盘统计数据", notes = "统计数据包括网盘总容量，已使用容量，单位是KB，请注意，返回的时候1KB = 1024B")
    @ApiResponses({
            @ApiResponse(code = 1001, message = "请求成功"),
            @ApiResponse(code = 500, message = "请求失败")
    })
    public Response diskStat(){
        String identification = SecurityUtils.getSubject().getPrincipal().toString();
        HashMap<String, Integer> data = new HashMap<>();
        Response res = new Response(data);
        String[] quota_command = {"quota", "-u", identification};
        try{
            Process execution = Runtime.getRuntime().exec(quota_command);
            BufferedReader input = new BufferedReader(new InputStreamReader(execution.getInputStream()));
            input.readLine();
            input.readLine();
            input.readLine();
	        String s = input.readLine();
            String[] results = s.split("\\s+");
            int used_size = Integer.parseInt(results[1]);
            data.put("used", used_size);
            int total_quota = Integer.parseInt(results[2]);
            data.put("quota", total_quota);
            res.setCode(1001);
            res.setMessage("查询成功");
            return res;
        }catch(Exception e){
            res.setCode(500);
            res.setMessage("查询失败");
            return res;
        }
    }

    @PostMapping("/resize")
    @ApiOperation(value = "用来给网盘扩配", notes = "不要往小了调，可能会有问题")
    @ApiResponses({
            @ApiResponse(code = 1001, message = "扩配成功"),
            @ApiResponse(code = 500, message = "扩配失败")
    })
    public Response resize(@RequestParam("NewSize") @ApiParam(value = "新的网盘大小，单位是MB") int new_size){
        String identification = SecurityUtils.getSubject().getPrincipal().toString();
        HashMap<String, Object> data = new HashMap<>();
        Response res = new Response(data);
        try{
            String[] resize = {"/home/buaa/jobs/quota_resize", identification, String.valueOf(new_size)};
            Runtime.getRuntime().exec(resize);
            res.setCode(1001);
            res.setMessage("扩配成功");
            logger.info(identification+" has resized net disk to "+new_size+"MB");
        }catch(Exception e){
            res.setCode(500);
            res.setMessage("扩配失败");
            logger.error("Error occurred when "+identification+" tries to resize the disk with stack trace "+e.toString());
        }
        return res;
    }

}
